// 页面内的调试器界面
let debugPanel = null;
let isDebugPanelVisible = false;
let debugData = [];

// 存储 WebSocket 连接状态和实例
let wsConnection = null;
let debuggerState = {
    connected: false,
    url: '',
    lastError: '',
    debugData: []
};

// 初始化调试面板
function initDebugPanel() {
    if (debugPanel) {
        return;
    }

    // 创建调试面板
    debugPanel = document.createElement('div');
    debugPanel.id = 'ws-debugger-panel';
    debugPanel.style.cssText = `
    position: fixed;
    bottom: 0;
    right: 0;
    width: 400px;
    height: 300px;
    background-color: rgba(0, 0, 0, 0.8);
    color: #fff;
    font-family: monospace;
    z-index: 9999;
    display: flex;
    flex-direction: column;
    border-top-left-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
    font-size: 12px;
    overflow: hidden;
  `;

    // 创建标题栏
    const titleBar = document.createElement('div');
    titleBar.style.cssText = `
    padding: 8px;
    background-color: #333;
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: move;
    user-select: none;
  `;

    const title = document.createElement('div');
    title.textContent = 'WebSocket 调试器';
    title.style.fontWeight = 'bold';

    const closeButton = document.createElement('button');
    closeButton.textContent = '×';
    closeButton.style.cssText = `
    background: none;
    border: none;
    color: #fff;
    font-size: 16px;
    cursor: pointer;
  `;
    closeButton.onclick = toggleDebugPanel;

    titleBar.appendChild(title);
    titleBar.appendChild(closeButton);

    // 创建内容区域
    const content = document.createElement('div');
    content.style.cssText = `
    flex: 1;
    overflow-y: auto;
    padding: 8px;
  `;
    content.id = 'ws-debugger-content';

    // 创建状态栏
    const statusBar = document.createElement('div');
    statusBar.style.cssText = `
    padding: 8px;
    background-color: #333;
    display: flex;
    justify-content: space-between;
    font-size: 11px;
  `;
    statusBar.id = 'ws-debugger-status';
    statusBar.textContent = '状态：未连接';

    // 组装面板
    debugPanel.appendChild(titleBar);
    debugPanel.appendChild(content);
    debugPanel.appendChild(statusBar);

    // 让面板可拖动
    let isDragging = false;
    let dragOffsetX, dragOffsetY;

    titleBar.addEventListener('mousedown', (e) => {
        isDragging = true;
        dragOffsetX = e.clientX - debugPanel.getBoundingClientRect().left;
        dragOffsetY = e.clientY - debugPanel.getBoundingClientRect().top;
    });

    document.addEventListener('mousemove', (e) => {
        if (!isDragging) return;

        const x = e.clientX - dragOffsetX;
        const y = e.clientY - dragOffsetY;

        debugPanel.style.left = `${x}px`;
        debugPanel.style.right = 'auto';
        debugPanel.style.top = `${y}px`;
        debugPanel.style.bottom = 'auto';
    });

    document.addEventListener('mouseup', () => {
        isDragging = false;
    });

    // 将面板添加到页面
    document.body.appendChild(debugPanel);

    // 初始隐藏
    debugPanel.style.display = 'none';
}

// 显示或隐藏调试面板
function toggleDebugPanel() {
    if (!debugPanel) {
        initDebugPanel();
    }

    isDebugPanelVisible = !isDebugPanelVisible;
    debugPanel.style.display = isDebugPanelVisible ? 'flex' : 'none';

    if (isDebugPanelVisible) {
        updateDebugPanel();
    }
}

// 更新调试面板内容
function updateDebugPanel() {
    if (!debugPanel || !isDebugPanelVisible) {
        return;
    }

    const content = document.getElementById('ws-debugger-content');
    content.innerHTML = '';

    if (debugData.length === 0) {
        content.textContent = '暂无调试数据';
        return;
    }

    // 显示最新的 20 条数据
    const recentData = debugData.slice(-20);

    recentData.forEach((item, index) => {
        const itemElement = document.createElement('div');
        itemElement.style.cssText = `
      padding: 5px;
      border-bottom: 1px solid #444;
      margin-bottom: 5px;
    `;

        const timestamp = document.createElement('div');
        timestamp.style.color = '#999';
        timestamp.style.fontSize = '10px';
        timestamp.textContent = `[${new Date().toLocaleTimeString()}]`;

        const data = document.createElement('pre');
        data.style.margin = '3px 0';
        data.style.whiteSpace = 'pre-wrap';
        data.style.wordBreak = 'break-all';
        data.textContent = JSON.stringify(item, null, 2);

        itemElement.appendChild(timestamp);
        itemElement.appendChild(data);
        content.appendChild(itemElement);
    });

    // 滚动到底部
    content.scrollTop = content.scrollHeight;
}

// 更新状态栏
function updateStatus(message) {
    if (!debugPanel) {
        return;
    }

    const statusBar = document.getElementById('ws-debugger-status');
    if (statusBar) {
        statusBar.textContent = `状态：${message}`;
    }
}

// 添加调试数据
function addDebugData(data) {
    debugData.push(data);
    if (debugData.length > 100) {
        debugData.shift();
    }
    updateDebugPanel();
}

// 监听来自 background 的消息
chrome.runtime.onMessage.addListener((message) => {
    if (message.type === 'debug_data') {
        addDebugData(message.data);
    } else if (message.type === 'connection_status') {
        if (message.status === 'connected') {
            updateStatus('已连接');
        } else if (message.status === 'disconnected') {
            updateStatus('未连接');
        } else if (message.status === 'error') {
            updateStatus(`错误：${message.error || 'Unknown error'}`);
        }
    }
});

// 创建悬浮按钮以显示/隐藏调试面板
function createFloatingButton() {
    const button = document.createElement('div');
    button.id = 'ws-debugger-button';
    button.style.cssText = `
    position: fixed;
    bottom: 20px;
    right: 20px;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background-color: #4285f4;
    color: white;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    z-index: 9998;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
    font-size: 24px;
    font-weight: bold;
    font-family: monospace;
  `;
    button.textContent = 'DB';
    button.title = 'Toggle WebSocket Debugger';

    button.addEventListener('click', toggleDebugPanel);
    document.body.appendChild(button);
}

// 初始化，在 DOM 加载完成后执行
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', createFloatingButton);
} else {
    createFloatingButton();
}

// 检查页面上是否存在调试相关参数
function checkForDebuggerParams() {
    const url = new URL(window.location.href);
    const showDebugger = url.searchParams.get('showDebugger');

    if (showDebugger === 'true') {
        setTimeout(() => {
            // 保证在页面加载后显示
            if (!isDebugPanelVisible) {
                toggleDebugPanel();
            }
        }, 1000);
    }
}

// 页面加载时检查调试参数
checkForDebuggerParams();

// 处理连接到 WebSocket 服务器
function connectToWebSocket(url) {
    if (wsConnection) {
        wsConnection.close();
    }

    try {
        wsConnection = new WebSocket(url);

        // 更新状态为正在连接
        debuggerState.url = url;
        saveDebuggerState();

        // 设置 WebSocket 事件处理
        wsConnection.onopen = () => {
            console.log('WebSocket 连接已建立');
            debuggerState.connected = true;
            debuggerState.lastError = '';
            saveDebuggerState();
            broadcastToClients({ type: 'connection_status', status: 'connected' });
        };

        wsConnection.onmessage = (event) => {
            console.log('收到消息：', event.data);
            try {
                const data = JSON.parse(event.data);
                // 将收到的调试数据存储到状态中
                debuggerState.debugData.push(data);
                if (debuggerState.debugData.length > 100) {
                    // 限制存储数据数量
                    debuggerState.debugData.shift();
                }
                saveDebuggerState();

                // 转发消息到内容脚本
                broadcastToClients({
                    type: 'debug_data',
                    data: data
                });
            } catch (e) {
                console.error('解析消息失败：', e);
            }
        };

        wsConnection.onclose = () => {
            console.log('WebSocket 连接已关闭');
            debuggerState.connected = false;
            saveDebuggerState();
            broadcastToClients({ type: 'connection_status', status: 'disconnected' });
            wsConnection = null;
        };

        wsConnection.onerror = (error) => {
            console.error('WebSocket 错误：', error);
            debuggerState.lastError = 'Connection error';
            debuggerState.connected = false;
            saveDebuggerState();
            broadcastToClients({
                type: 'connection_status',
                status: 'error',
                error: 'Connection error'
            });
        };

        return { success: true };
    } catch (error) {
        console.error('创建 WebSocket 连接失败：', error);
        debuggerState.lastError = error.message;
        debuggerState.connected = false;
        saveDebuggerState();
        return { success: false, error: error.message };
    }
}

// 断开 WebSocket 连接
function disconnectWebSocket() {
    if (wsConnection) {
        wsConnection.close();
        wsConnection = null;
        debuggerState.connected = false;
        saveDebuggerState();
        return { success: true };
    }
    return { success: false, error: 'No active connection' };
}

// 发送消息到 WebSocket 服务器
function sendMessageToServer(message) {
    if (wsConnection && wsConnection.readyState === WebSocket.OPEN) {
        wsConnection.send(JSON.stringify(message));
        return { success: true };
    }
    return {
        success: false,
        error: 'WebSocket not connected'
    };
}

// 广播消息到所有内容脚本
async function broadcastToClients(message) {
    try {
        const tabs = await chrome.tabs.query({});
        for (const tab of tabs) {
            try {
                chrome.tabs.sendMessage(tab.id, message);
            } catch (e) {
                // 忽略发送消息失败的 tab
                console.log(`向 tab ${tab.id} 发送消息失败`);
            }
        }
    } catch (error) {
        console.error('广播消息失败：', error);
    }
}

// 保存调试器状态到存储
function saveDebuggerState() {
    chrome.storage.local.set({ debuggerState });
}

// 加载调试器状态
function loadDebuggerState() {
    chrome.storage.local.get('debuggerState', (result) => {
        if (result.debuggerState) {
            debuggerState = result.debuggerState;

            // 如果之前是连接状态，尝试重新连接
            if (debuggerState.connected && debuggerState.url) {
                connectToWebSocket(debuggerState.url);
            }
        }
    });
}

// 监听来自弹出窗口或内容脚本的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    console.log('收到消息：', message);

    if (message.type === 'connect') {
        const result = connectToWebSocket(message.url);
        sendResponse(result);
    } else if (message.type === 'disconnect') {
        const result = disconnectWebSocket();
        sendResponse(result);
    } else if (message.type === 'send_command') {
        const result = sendMessageToServer(message.command);
        sendResponse(result);
    } else if (message.type === 'get_status') {
        sendResponse({
            connected: debuggerState.connected,
            url: debuggerState.url,
            lastError: debuggerState.lastError
        });
    } else if (message.type === 'get_debug_data') {
        sendResponse({
            data: debuggerState.debugData
        });
    } else if (message.type === 'execute_browser_command') {
        try {
            // 处理特定命令，根据需要扩展这部分
            if (message.command === 'clearCookies') {
                chrome.cookies.getAll({}, function(cookies) {
                    for (var i = 0; i < cookies.length; i++) {
                        chrome.cookies.remove({ url: "http://" + cookies[i].domain + cookies[i].path, name: cookies[i].name });
                    }
                    sendResponse({ success: true, result: '已清除所有 cookies' });
                });
                return true;
            } else if (message.command.startsWith('navigate:')) {
                const url = message.command.split(':')[1];
                chrome.tabs.update(sender.tab.id, { url: url });
                sendResponse({ success: true, result: `正在导航到 ${url}` });
            } else if (message.command === 'reload') {
                chrome.tabs.reload(sender.tab.id);
                sendResponse({ success: true, result: '页面刷新中' });
            } else {
                // 对于未知命令，返回错误
                sendResponse({ success: false, error: '未知命令' });
            }
        } catch (error) {
            sendResponse({ success: false, error: error.message });
        }
        return true;
    }

    // 返回 true 表示异步发送响应
    return true;
});

// 初始化时加载状态
loadDebuggerState();